package com.siwei.mes.sync.erp.service.impl;

import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.CheckTypeEnum;
import com.siwei.mes.enums.CreateTypeEnum;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.service.experiment.ExperimentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成混凝土快检
 *
 * @Description: 生成混凝土快检
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/11 21:45
 */
@Service
public class GenQuickExperimentService extends GenAbstractService {
    private static final Logger log = LoggerFactory.getLogger("erp");

    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentQuickRecordMapper experimentQuickRecordMapper;
    @Resource
    private CheckQuickConfigMapper checkQuickConfigMapper;

    /**
     * 生成混凝土快检  目前只有车车都检
     *
     * @param rwdextra           任务单信息
     * @param itemorder          小票信息
     * @param testProjectInfoMap 试验项目信息map
     */
    public Long genExperiment(Rwdextra rwdextra, Itemorder itemorder, Map<String, TestProjectInfo> testProjectInfoMap) {
        try {
            log.info("生成混凝土快检开始，任务单号：【{}】，小票id；【{}】", rwdextra.getFrwdh(), itemorder.getItid());
            ExperimentGenConfig config = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                    .setExperimentType(MaterialsEnum.CONCRETE.getCode()).setCheckType(CheckEnum.QUICK.getCode())
                    .setIsCustom(0));

            if (config == null || config.getIsOpen() == null || config.getIsOpen() == 0) {
                log.info("混凝土快检生成委托规则配置为空或未开启，暂不生成，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            String phbNo = rwdextra.getPhbshow();

            log.info("开始组装混凝土【快检】对应试验委托，配合比号：【{}】，任务单号：【{}】，小票id：：【{}】",
                    phbNo, rwdextra.getFrwdh(), itemorder.getItid());

            /**委托试验名称*/
            Set<String> entrustExperimentSet = new HashSet<>();
            /**试验项目code集合*/
            Set<String> testProjectCodeList = new HashSet<>();

            /**获取所有快检配置信息*/
            List<CheckQuickConfig> quickConfigList = checkQuickConfigMapper.select(new CheckQuickConfig().setIsDel(0).setProjectCategory(MaterialsEnum.CONCRETE.getCode()));
            if (quickConfigList.isEmpty()) {
                log.info("混凝土快检指标配置为空，暂不生成试验委托");
                return null;
            }
            /**获取所有试验项目配置*/
            List<TestProjectInfo> testProjectInfoList = new ArrayList<>();
            for (CheckQuickConfig quickConfig : quickConfigList) {
                /**放入试验项目code集合*/
                List<String> codeList = Arrays.asList(quickConfig.getTestProjectCode().split(","));
                testProjectCodeList.addAll(codeList);
                for (String code : codeList) {
                    TestProjectInfo testProjectInfo = testProjectInfoMap.get(code);
                    if (testProjectInfo != null) {
                        testProjectInfoList.add(testProjectInfo);
                    }
                }
                /**放入委托试验名称*/
                List<String> nameList = Arrays.asList(quickConfig.getTestProjectName().split(","));
                entrustExperimentSet.addAll(nameList);
            }

            /**混凝土快检目前只有车车都检*/
            Integer checkRules = config.getCheckRules();
            if (checkRules == 1) {
                String entrustExperiment = entrustExperimentSet.isEmpty() ? null : entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));

                /**新增混凝土试验台账*/
                Experiment experiment = experimentService.getExperimentInfoByItemOrderInfo(itemorder, CheckEnum.QUICK.getCode(), entrustExperiment, testProjectCodeList);
                experiment.setPhb(phbNo);
                experiment.setFactory(itemorder.getMixtable());

                /**组装物料相关信息*/
                super.payloadMaterialsInfo(itemorder.getTpz(), experiment);
                experiment.setCreateType(CreateTypeEnum.DEFAULT_CHECK.getCode()).setCreateCheckType(CheckTypeEnum.DEFAULT_CHECK.getCode());
                experimentMapper.insertSelective(experiment);

                /**这里赋值对应的试验台账信息*/
                Long experimentId = experiment.getId();

                if (!testProjectCodeList.isEmpty()) {
                    List<ExperimentDetail> detailList = new ArrayList<>();
                    /**查询所有试验项目信息*/
                    for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                        ExperimentDetail detail = new ExperimentDetail();
                        detail.setExperimentId(experiment.getId());
                        detail.setCheckType(CheckEnum.QUICK.getCode());
                        detail.erpInit(true);
                        detail.setTestProjectCode(testProjectInfo.getTestCode());
                        detail.setTestProjectName(testProjectInfo.getTestName());
                        detail.setObjJson(testProjectInfo.getObjJson());
                        detailList.add(detail);
                    }
                    if (!detailList.isEmpty()) {
                        /**生成对应试验台账详情信息*/
                        experimentDetailMapper.insertList(detailList);
                    }

                    /**新增对应快检的抽样信息  对应快检的所有的项目集合只有一条数据 */
                    ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                    sampleSmoke.setId(null);
                    sampleSmoke.erpInit(true);
                    sampleSmoke.setExperimentId(experiment.getId());
                    sampleSmoke.setSampleTime(new Date());
                    sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                    sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                    sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());

                    StringBuilder testProjectCode = new StringBuilder();
                    StringBuilder testProjectName = new StringBuilder();

                    for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                        testProjectCode.append(testProjectInfo.getTestCode()).append(",");
                        testProjectName.append(testProjectInfo.getTestName()).append(",");
                    }
                    if (testProjectCode.length() > 0) {
                        String code = testProjectCode.deleteCharAt(testProjectCode.length() - 1).toString();
                        sampleSmoke.setTestProjectCode(code);
                    }
                    if (testProjectName.length() > 0) {
                        String name = testProjectName.deleteCharAt(testProjectName.length() - 1).toString();
                        sampleSmoke.setTestProjectName(name);
                        sampleSmoke.setSampleUse(name);
                    }
                    experimentSampleSmokeMapper.insertSelective(sampleSmoke);
                }


                /**新增试验台账对应快检配置记录*/
                for (CheckQuickConfig quickConfig : quickConfigList) {
                    experimentQuickRecordMapper.insertSelective(new ExperimentQuickRecord().erpInit(true).setExperimentId(experimentId).setQuickId(quickConfig.getId()));
                }
                /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
                super.insertExperimentRelatedRecords(experimentId, itemorder.getItid(), rwdextra.getFrwdh());
                /**修改试验台账的代表数量*/
                super.updateExperimentBehalfNumber(experimentId);
                log.info("生产混凝土快检完成！对应试验委托id：【{}】", experimentId);
                return experimentId;
            } else {
                log.info("目前混凝土快检只支持车车都检，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
            }
        } catch (Exception e) {
            super.handleException("混凝土生成快检失败", e);
            return null;
        }
        log.info("生成混凝土快检结束");
        return null;
    }

}
